package handler

import (
	"litetalk/config"
	"litetalk/proto"
	"net/http"

	"github.com/gin-gonic/gin"
)

func TokenAuthMiddleware(c *gin.Context) {
	args := &proto.CheckAuthReq{
		AuthToken: c.GetHeader("authToken"),
	}
	reply := &proto.CheckAuthRep{}
	if err := logicRpc.CheckAuth(args, reply); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	c.Next()
}

func CoreMiddleware(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
	c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT")
	c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
	c.Header("Access-Control-Allow-Credentials", "true")
	if c.Request.Method == "OPTIONS" {
		c.AbortWithStatus(http.StatusNoContent)
	}
	c.Next()
}

func ApiMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		enable, has := config.Conf.Api.WhiteList[c.ClientIP()]
		if has && enable {
			c.Next()
		} else {
			c.AbortWithStatusJSON(http.StatusNotAcceptable, gin.H{
				"message": "Your IP not int whitelist!",
			})
		}
	}
}
